import React, { Component } from 'react'
import ReactDOM from 'react-dom';
import { Modal, Form, Table, Button, message, Row, Col } from 'antd';
import { fetchData } from '../../../components/AjaxConsumer'
// import PrintFrom from './PrintFrom'

import styles from './index_ad.scss';

const confirm = Modal.confirm;

export default class PrintHandle extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            formTitle: '',
            visible: false,
            ifPrintBtn: true,
            columns:[],
            data:[],
            sellOutData: [],
            rowData: null,
            suburl: '/product/prosellout/print',
            tableArr: [],
            tableColumns: []
        };
        this.currentPage  = 1;
        this.currentPageSize = 30;
    }

    //显示弹框
    showModal = () => {
        this.setState({
            visible: true,
            ifPrintBtn: true,
        });
    }

    // 隐藏弹出框
    hideModal = () => {
        this.setState({
            visible: false,
        });
    }

    printHandle = (rowObj) => {

        this.setState({
            visible: true,
            formTitle: '',
            rowData: rowObj[0].data,
            sellOutNo: rowObj[0].data.sellOutNo
        });
        // console.info("sellOutNO:" + rowObj[0].data.sellOutNo);
        // console.info("sellOut=====:" + this.state.sellOutNO);
        const options = {
            url: this.state.suburl,
            type: 'post',
            condition: {sellOutNo: rowObj[0].data.sellOutNo}
        };

        fetchData(this, options, (res) => {
            //成功回调函数
            this.setState({
                loading: false
            });
            if (res.code == '1') {
                // message.success('操作成功');
                console.log("res",res);
                this.setState({
                    sellOutData: res.list[0],
                    data: res.list[0].proSellOutSns
                })
                let Allcolums = this.mergeTablehadle(res.list[0].proSellOutSns);
                // console.log("sellOutData.proSellOutSns:", this.state.data);
                let tableArr = [];
                let curData = [];
                
                if(this.state.data.length > this.currentPageSize){
                    this.state.data.map((value,index)=>{
                        curData.push(value);
                        if(index != 0 && (index + 1) % this.currentPageSize == 0 || index == this.state.data.length - 1){
                            tableArr.push(curData);
                            curData = [];
                        }
                    });
                }else{
                    tableArr.push(this.state.data);
                }

                this.setState({
                    tableArr: tableArr,
                    columns: Allcolums
                });

                // console.log('tableArr',tableArr);
                // console.log('columns',Allcolums);

                let tableColumns = [];
                tableArr.map((table,index)=>{
                   let curColums = this.mergeTablehadle(table);
                   tableColumns.push(curColums);
                });
                this.setState({
                    tableColumns: tableColumns
                });
               
                // this.handleCancel();
                // this.props.refreshHandle();
                
            } else {
               //message.error(res.msg);
            }

        },
            (res) => {
                this.setState({
                    loading: false
                });
            }
        )
    } 


    mergeTablehadle = (data) => {
        let model = '',
            codeNum = '',
            codeWt = '',
            rowSpanNumber1 = 1,
            rowSpanNumber2 = 1,
            rowSpanNumber3 = 1,
            mergeObj1 = {},
            mergeObj2 = {},
            mergeObj3 = {};
    
        //获取行合并的数值
        console.log('mergeTablehadle-----',this.state.data);
        console.log('mergeTablehadle--data---',data);
        data.map((item, index) => {
            // 型号
            if (model === '') {
                model = item.model;
            } else if (model === item.model) {
                rowSpanNumber1++;
                //型号：2-5，2代表[型号]需要合并几行， 5 代表从第几行开始合并
                mergeObj1[item.model] = rowSpanNumber1 + "-" + (index - rowSpanNumber1 + 1);
            } else if (model !== item.model) {
                rowSpanNumber1 = 1;
                model = item.model;
            }
    
            // 合计件数  codeNum [多条件行合并]
            if (codeNum === '') {
                codeNum = item.model + item.codeNum;
            } else if (codeNum === (item.model + item.codeNum)) {
                rowSpanNumber2++;
                mergeObj2[item.model + item.codeNum] = rowSpanNumber2 + "-" + (index - rowSpanNumber2 + 1);
            } else if (codeNum !== item.model + item.codeNum) {
                rowSpanNumber2 = 1;
                codeNum = item.model + item.codeNum;
            }
    
            // 合计重量 [多条件行合并]
            if (codeWt === '') {
                codeWt = item.model + item.codeWt;
            } else if (codeWt === (item.model + item.codeWt)) {
                rowSpanNumber3++;
                mergeObj3[item.model + item.codeWt] = rowSpanNumber3 + "-" + (index - rowSpanNumber3 + 1);
            } else if (codeWt !== item.model + item.codeWt) {
                rowSpanNumber3 = 1;
                codeWt = item.model + item.codeWt;
            }
        });

    
        let columns = this.setcolumns(mergeObj1, mergeObj2, mergeObj3);
        return columns;
    }
    
    setcolumns = (mergeObj1, mergeObj2, mergeObj3) => {
        let model = "";
    
        // 型号
        const renderContent1 = (value, row, index) => {
            model = value;
            const obj = {
                children: value,
                props: {},
            };
            if (mergeObj1[value] !== undefined) {
                let merge = mergeObj1[value].split("-");
                let rowSpanNumber = parseInt(merge[0]);
                let mergeIndexStart = parseInt(merge[1]);
                let mergeIndexEnd = parseInt(mergeIndexStart) + parseInt(rowSpanNumber);
    
                let AllIndex = (this.currentPage - 1) * this.currentPageSize + index;
                
                // console.log('mergeIndexStart--',mergeIndexStart,'AllIndex',AllIndex,'---mergeIndexEnd--',mergeIndexEnd);
                if (AllIndex < this.pageSize) {
                    // Table首页
                    if (index === mergeIndexStart) {
                        obj.props.rowSpan = rowSpanNumber;
                    } else if (mergeIndexStart < index && index < mergeIndexEnd) {
                        obj.props.rowSpan = 0;
                    } else {
                        obj.props.rowSpan = 1;
                    }
                } else {
                    // Table第二页及之后，可能有断页合并
                    if (AllIndex == mergeIndexStart) {
                        // 正常合并项第一个
                        obj.props.rowSpan = rowSpanNumber;
                    } else if (index == 0 && mergeIndexStart < AllIndex < mergeIndexEnd) {
                        // 页面首行且为断页合并范围
                        obj.props.rowSpan = mergeIndexEnd - AllIndex;
                    } else if (mergeIndexStart < AllIndex < mergeIndexEnd) {
                        obj.props.rowSpan = 0;
                    } else {
                        obj.props.rowSpan = 1;
                    }
                }
            }
            return obj;
        };
    
        // 合计件数
        const renderContent2 = (value, row, index) => {
            const obj = {
                children: value,
                props: {},
            };
            if (mergeObj2[model + value] !== undefined) {
                let merge = mergeObj2[model + value].split("-");
                let rowSpanNumber = parseInt(merge[0]);
                let mergeIndexStart = parseInt(merge[1]);
                let mergeIndexEnd = parseInt(mergeIndexStart) + parseInt(rowSpanNumber);
    
                let AllIndex = (this.currentPage - 1) * this.currentPageSize + index;
               
                if (AllIndex < this.pageSize) {
                    // Table首页
                    if (index === mergeIndexStart) {
                        obj.props.rowSpan = rowSpanNumber;
                    } else if (mergeIndexStart < index && index < mergeIndexEnd) {
                        obj.props.rowSpan = 0;
                    } else {
                        obj.props.rowSpan = 1;
                    }
                } else {
                    // Table第二页及之后，可能有断页合并
                    if (AllIndex == mergeIndexStart) {
                        // 正常合并项第一个
                        obj.props.rowSpan = rowSpanNumber;
                    } else if (index == 0 && mergeIndexStart < AllIndex < mergeIndexEnd) {
                        // 页面首行且为断页合并范围
                        obj.props.rowSpan = mergeIndexEnd - AllIndex;
                    } else if (mergeIndexStart < AllIndex < mergeIndexEnd) {
                        obj.props.rowSpan = 0;
                    } else {
                        obj.props.rowSpan = 1;
                    }
                }
            }
            return obj;
        };
    
        // 合计重量
        const renderContent3 = (value, row, index) => {
            const obj = {
                children: value,
                props: {},
            };

            if (mergeObj3[model + value] !== undefined) {
                let merge = mergeObj3[model + value].split("-");
                let rowSpanNumber = parseInt(merge[0]);
                let mergeIndexStart = parseInt(merge[1]);
                let mergeIndexEnd = parseInt(mergeIndexStart) + parseInt(rowSpanNumber);
    
                let AllIndex = (this.currentPage - 1) * this.currentPageSize + index;

                // console.log('mergeIndexStart--',mergeIndexStart,'AllIndex',AllIndex,'---mergeIndexEnd--',mergeIndexEnd);
    
                if (AllIndex < this.pageSize) {
                    // Table首页
                    if (index === mergeIndexStart) {
                        obj.props.rowSpan = rowSpanNumber;
                    } else if (mergeIndexStart < index && index < mergeIndexEnd) {
                        obj.props.rowSpan = 0;
                    } else {
                        obj.props.rowSpan = 1;
                    }
                } else {
                    // Table第二页及之后，可能有断页合并
                    if (AllIndex == mergeIndexStart) {
                        // 正常合并项第一个
                        obj.props.rowSpan = rowSpanNumber;
                    } else if (index == 0 && mergeIndexStart < AllIndex < mergeIndexEnd) {
                        // 页面首行且为断页合并范围
                        obj.props.rowSpan = mergeIndexEnd - AllIndex;
                    } else if (mergeIndexStart < AllIndex < mergeIndexEnd) {
                        obj.props.rowSpan = 0;
                    } else {
                        obj.props.rowSpan = 1;
                    }
                }
            }
            return obj;
        };
    
        let columns = [
            {
                title: '型号',
                dataIndex: 'model',
                width: 200,
                render: renderContent1
            }
            , {
                title: '条码',
                dataIndex: 'barcode',
                width: 200,
            }
            , {
                title: '重量',
                dataIndex: 'weight',
                width: 150,
            }
            , {
                title: '仓库',
                dataIndex: 'waCode',
                width: 90,
            }
            , {
                title: '机号',
                dataIndex: 'machineNumber',
                width: 80,
            }
            , {
                title: '等级',
                dataIndex: 'grade',
                width: 80,
            }
            , {
                title: '合计件',
                dataIndex: 'codeNum',
                width: 100,
                render: renderContent2
    
            }
            , {
                title: '合计重',
                dataIndex: 'codeWt',
                width: 150,
                render: renderContent3
            }
        ];
        return columns;
    };

    handleOk = () => {
        this.hideModal();
        this.refreshHandle();
    }

    handleCancel = () => {
        //表单重置
        // this.refs.printFrom.resetFields();
        this.hideModal();
    }

    //刷新List列表
    refreshHandle = () => {
        console.log("刷新List列表")
        this.props.refreshHandle();
    }


    printAll = () =>{

        // $("#printImg").css("display", "none");
        //     window.print();
        // $("#printImg").css("display", "");

        $("body").removeClass("baseWidthSet");
        $("body").addClass("printNew");
        let prnhtml = document.getElementById('AllPagesPrint').innerHTML;
        document.body.innerHTML = prnhtml;
        window.print(); 
        window.location.reload();
        
    }

    changePage = (current, pageSize) => {
        this.currentPage = current;
        this.currentPageSize = pageSize;
    }

    render() {
        let sellOutPrint = this.state.sellOutData;
        console.log('this.state.ifPrintBtn---',this.state.ifPrintBtn);
        const pagination = {
            useFixedHeader: true, // 固定表头
            pageSize: 30,
            onChange: this.changePage
        };

        let keys = this.state.tableArr;
        const formItems = keys.map((value,index)=>{
            return(
                <div className={styles.nextPrint}>
                    <div className={styles.modelTopTable}> 
                        {/* <Row>
                            <Col span={8}>
                                发货单号：{sellOutPrint.sellOutNo}
                            </Col>
                            <Col span={5}>
                                货主：{sellOutPrint.userDefined1}
                            </Col>
                            <Col span={5}>
                            箱号：{sellOutPrint.userDefined3}
                            </Col>
                            <Col span={6}>
                            车牌：{sellOutPrint.userDefined2}
                            </Col>
                        </Row>
                        <Row>
                            <Col span={8}>
                                出库日期：{sellOutPrint.sellOutTime?sellOutPrint.sellOutTime.substring(0,10):''}
                            </Col>
                            <Col span={5}>
                                总件数：{Number(sellOutPrint.totalNum)}
                            </Col>
                            <Col span={5}>
                                总重量：{Number(sellOutPrint.totalWt)}
                            </Col>
                            <Col span={6}>
                                记录员：{sellOutPrint.lastModifiedBy}
                            </Col>
                        </Row> */}
                        <Row>
                            <Col span={8}>
                            &nbsp;发货单号：{sellOutPrint.sellOutNo}
                            </Col>
                            <Col span={8}>
                                厂名：桐乡福利造纸厂
                            </Col>
                            <Col span={8}>
                                出库日期：{sellOutPrint.sellOutTime?sellOutPrint.sellOutTime.substring(0,10):''}
                            </Col>
                        </Row>
                        <Row>
                            <Col span={8}>
                            &nbsp;货主：{sellOutPrint.userDefined1}
                            </Col>
                            <Col span={8}>
                                车牌：{sellOutPrint.userDefined2}
                            </Col>
                            <Col span={8}>
                                箱号：{sellOutPrint.userDefined3}
                            </Col>
                        </Row>
                        <Row>
                            <Col span={8}>
                            &nbsp;总件数：{Number(sellOutPrint.totalNum)}
                            </Col>
                            <Col span={8}>
                                总重量：{Number(sellOutPrint.totalWt)}
                            </Col>
                            <Col span={8}>
                                记录员：{sellOutPrint.lastModifiedBy}
                            </Col>
                        </Row>
                    </div>
                    <Table 
                        className={styles.printTable}
                        rowKey={record => record.proDbOutId}
                        columns={this.state.tableColumns[index]}
                        dataSource={this.state.tableArr[index]}
                        bordered
                        pagination={pagination}
                    >
                    </Table>
                </div>
            )
        });
        return (
            <Modal
                style={{ top: '20px'}}
                visible={this.state.visible}
                title={this.state.formTitle ? this.state.formTitle : ''}
                onOk={this.handleOk}
                onCancel={this.handleCancel}
                width={ '1050px' }
                footer=''
            >

              <div className={styles.printPage} id="AllPagesPrint">
                {formItems}
              </div>

              <Row span={6} offset={18}>
                <Button id="printImg" onClick={this.printAll}>打印</Button>
              </Row>

                <div className={styles.modelTopTable}> 
                    {/* <Row>
                        <Col span={8}>
                            发货单号：{sellOutPrint.sellOutNo}
                        </Col>
                        <Col span={6}>
                            货主：{sellOutPrint.userDefined1}
                        </Col>
                        <Col span={4}>
                            箱号：{sellOutPrint.userDefined3}
                        </Col>
                        <Col span={5}>
                            车牌：{sellOutPrint.userDefined2}
                        </Col>
                    </Row>
                    <Row>
                        <Col span={8}>
                            出库日期：{sellOutPrint.sellOutTime?sellOutPrint.sellOutTime.substring(0,10):''}
                        </Col>
                        <Col span={5}>
                            总件数：{Number(sellOutPrint.totalNum)}
                        </Col>
                        <Col span={6}>
                            总重量：{Number(sellOutPrint.totalWt)}
                        </Col>
                        <Col span={5}>
                            记录员：{sellOutPrint.lastModifiedBy}
                        </Col>
                    </Row> */}
                    <Row>
                        <Col span={8}>
                        &nbsp;发货单号：{sellOutPrint.sellOutNo}
                        </Col>
                        <Col span={8}>
                            厂名：桐乡福利造纸厂
                        </Col>
                        <Col span={8}>
                            出库日期：{sellOutPrint.sellOutTime?sellOutPrint.sellOutTime.substring(0,10):''}
                        </Col>
                    </Row>
                    <Row>
                        <Col span={8}>
                        &nbsp;货主：{sellOutPrint.userDefined1}
                        </Col>
                        <Col span={8}>
                            车牌：{sellOutPrint.userDefined2}
                        </Col>
                        <Col span={8}>
                            箱号：{sellOutPrint.userDefined3}
                        </Col>
                    </Row>
                    <Row>
                        <Col span={8}>
                        &nbsp;总件数：{Number(sellOutPrint.totalNum)}
                        </Col>
                        <Col span={8}>
                            总重量：{Number(sellOutPrint.totalWt)}
                        </Col>
                        <Col span={8}>
                            记录员：{sellOutPrint.lastModifiedBy}
                        </Col>
                    </Row>
                </div>
                <Table 
                    className={styles.printTable}
                    rowKey={record => record.proDbOutId}
                    columns={this.state.columns}
                    dataSource={this.state.data}
                    bordered
                    pagination={pagination}
                >
                </Table>
                    
                
            </Modal>
        )
    }
}